// templates/deliver/pages/location/location.js
import Notify from '@vant/weapp/notify/notify';
import {clearUserLocalStorage} from "../../../../utils/util";
const { authorization } = require('../../../../utils/location')
const app = getApp();


Page({

    /**
     * 页面的初始数据
     */
    data: {
        orders: [],
        markers: [],
        selected_ids: [],
        select_all_status: false,


        count: 0,
        area: '', //获取区域
        scale: 12.1,
        activeNames: ['1'],// 打开信息 按钮
        latitude: 0,   //获取当前位置
        longitude: 0,
        checked: true,
        image: '/templates/deliver/img/business.png',

        total_deliver_fee: 0,
        showCal: false,
        showDate: '',
        date: 0,
        minDate: new Date(2010, 0, 1).getTime(),
        maxDate: new Date(2010, 0, 31).getTime(),
    },

    onCalDisplay() {

        let date = new Date();
        this.setData({ showCal: true, date: date.getTime() });
    },
    onCalClose() {
        this.setData({ showCal: false });
    },
    formatDate(date) {
        date = new Date(date);
        return `${date.getMonth() + 1}月${date.getDate()}日`;
    },
    onCalConfirm(event) {
        let date = event.detail
        this.setData({
            showCal: false,
            showDate: this.formatDate(date),
            date: date
        });
        this.get_returned(date)
    },
    get_date_string(date) {
        // 如果date未定义，使用当前日期
        if (date === undefined) {
            date = new Date();
        }
        // 使用date参数获取年、月、日
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
    },

    /**
     * 生命周期函数--监听页面加载
     */ async onLoad(options) {
        let now = (new Date().getTime()) / 1000;
        let expiration_time = wx.getStorageSync('expiration_time')
        let group = wx.getStorageSync('role')

        let current_delivery_man_id = wx.getStorageSync('current_delivery_man_id')
        if (!current_delivery_man_id || current_delivery_man_id == 0) {
            current_delivery_man_id = 0
        }

        if (group !== 'delivery') {
            clearUserLocalStorage()
            expiration_time = 0
        }

        /*if (now > expiration_time) {
            wx.reLaunch({
                url: '/pages/login/login',
            })
        }*/

        let date = wx.getStorageSync('viewDeliveryDate')
        console.log('get date', date)
        let showDate = this.get_date_string(date)
        let minDate = new Date()
        // 将小时、分钟、秒和毫秒设置为0，如果你不需要时间部分
        minDate.setHours(0, 0, 0, 0);
        // 从当前月份中减去6个月
        minDate.setMonth(minDate.getMonth() - 6);
        minDate = minDate.getTime()
        let maxDate = date.getTime()

        let access_token = wx.getStorageSync('access_token')
        let delivery_man = wx.getStorageSync('delivery_man')
        let delivery_district = wx.getStorageSync('delivery_district')
        let delivery_district_list = wx.getStorageSync('delivery_district_list')
        let delivery_list = wx.getStorageSync('delivery_list')
        this.setData({
            'access_token': access_token,
            'delivery_man': delivery_man,
            'delivery_district': delivery_district,
            'delivery_district_list': delivery_district_list,
            'delivery_list': delivery_list,
            'current_delivery_district_id': 0,
            'level': delivery_man.level,
            'current_delivery_man_id': current_delivery_man_id,
            date: date.getTime(),
            showDate,
            minDate,
            maxDate
        })
        this.get_returned()
    },

    onCheck(e) {
        let orders = this.data.orders
        let selected_ids = e.detail
        let select_all_status = false
        if (selected_ids.length === orders.length) {
            select_all_status = true
        }
        this.setData({
            selected_ids,
            select_all_status
        })
    },

    call_mobile(e) {
        let mobile = e.currentTarget.dataset.mobile
        console.log(mobile)
        wx.makePhoneCall({
            phoneNumber: mobile,
            success: function () {
                console.log("拨打电话成功！")
            },
            fail: function () {
                console.log("拨打电话失败！")
            }
        })
    },

    onTapMarker(e) {
        const markerId = parseInt(e.detail.markerId)
        const markers = this.data.markers;

        console.log(markerId)
        const marker = markers.find(m => m.id === markerId); // 根据地图标记的 id 找到对应的 marker
        console.log(marker)
        if (marker) {
            const query = wx.createSelectorQuery();
            query.select(marker.select_id).boundingClientRect(); // 根据订单 id 找到对应的卡片
            query.exec(function(res) {
                console.log('res', res)
                const cardRect = res[0];
                if (cardRect) {
                    wx.pageScrollTo({
                        scrollTop: cardRect.top,
                    });
                }
            });
        }
    },

    tap_avatar(e) {
        console.log(e)
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
        })
        let latitude = e.currentTarget.dataset.latitude //获取传递的id参数
        let longitude = e.currentTarget.dataset.longitude //获取传递的id参数
        this.setData({
            'scale': 17,
        })
        this.map = wx.createMapContext('locationM', this)
        this.map.moveToLocation({
            longitude: Number(longitude),
            latitude: Number(latitude),
            success: function () {

            }
        })
    },

    select_all(event) {
        let orders = this.data.orders
        let selected_ids = []
        for (let i = 0; i < orders.length; i++) {
            selected_ids.push(String(orders[i]['id']))
        }
        this.setData({
            selected_ids: selected_ids,
            select_all_status: event.detail,
        })
        if (this.data.select_all_status === false) {
            this.setData({
                selected_ids: [],
            })
        }
        //console.log(this.data.result)
    },

    on_delivery_district_dropdown_change(e) {
        const current_delivery_district_id = e.detail;
        this.setData({
            current_delivery_district_id: current_delivery_district_id,
        });
        wx.setStorageSync('current_delivery_district_id', current_delivery_district_id);
        this.get_waiting_delivery();
    },
    on_delivery_dropdown_change(e) {
        const current_delivery_man_id = e.detail;
        this.setData({
            current_delivery_man_id: current_delivery_man_id,
        });
        wx.setStorageSync('current_delivery_man_id', current_delivery_man_id);
        //this.get_waiting_delivery();
    },

    async get_current_location() {
        let res = await authorization()
        console.log("authorization res", res)
        this.setData({
            'longitude': res.longitude,
            'latitude': res.latitude,
        })
        /*
        this.map.moveToLocation({
            longitude: Number(this.data.longitude),
            latitude: Number(this.data.latitude),
            success: function () {
                console.log("成功将地图中心移到定位点")
            }
        })
        */
    },



    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {



    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {



    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    onDisplay({
        detail
    }) {
        console.log({
            detail
        })
        var markers = this.data.markers;
        wx.showModal({
            title: '提示',
            content: '是否切换开关？',
            success: (res) => {
                console.log(res.confirm)
                if (!detail) {
                    for (var i = 0; i < markers.length; i++) {
                        this.setData({
                            ["markers[" + i + "].callout.display"]: 'BYCLICK',
                            checked: detail
                        });
                    }
                    this.setData({
                        checked: detail
                    });
                } else {
                    for (var i = 0; i < markers.length; i++) {
                        this.setData({
                            ["markers[" + i + "].callout.display"]: 'ALWAYS',

                        });
                    }
                    this.setData({
                        checked: detail
                    });
                }

            },
        });
    },

    onChangeShowCallout(event) {

        const {
            value
        } = event.detail;
        console.log(value)
        this.data.markers.forEach((item, index) => {

            if (value) {
                this.setData({

                    ["markers[" + index + "].callout.display"]: 'ALWAYS'

                });
            } else {
                this.setData({

                    ["markers[" + index + "].callout.display"]: 'BYCLICK'

                });
            }

        })


    },

    async finish_deliver() {
        const that = this
        let selected_ids = that.data.selected_ids

        wx.request({
            url: app.globalData.API + '/delivery/index/finish-deliver',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                selected_ids
            },
            success(res) {
                if (res.data.code == 200) {

                }
            }
        })
    },

    async get_returned() {
        const that = this
        let current_delivery_man_id = that.data.current_delivery_man_id
        let current_delivery_district_id = that.data.current_delivery_district_id
        let delivery_status = 1
        console.log('d',that.data.date)
        let timestamp = new Date(that.data.date)
        console.log('t',timestamp)
        let date = that.get_date_string(timestamp)
        console.log('d2',date)

        await that.get_current_location()
        wx.request({
            url: app.globalData.API + '/delivery/index/get-returned-orders',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                current_delivery_district_id,
                current_delivery_man_id,
                delivery_status,
                timestamp,
                date,
            },
            success(res) {
                if (res.data.code == 200) {
                    let orders = res.data.data.orders
                    let markers = []
                    for (let i = 0; i < orders.length; i++) {
                        const longitude = orders[i].longitude; // 经度
                        const latitude = orders[i].latitude; // 纬度
                        orders[i].latitude = latitude
                        orders[i].longitude = longitude
                        orders[i].distance = that.getDistance(latitude, longitude, that.data.latitude, that.data.longitude)
                    }
                    orders.sort((a, b) => a.distance - b.distance);
                    let total_deliver_fee = 0
                    for (let i = 0; i < orders.length; i++) {
                        total_deliver_fee += parseFloat(orders[i].deliver_fee)
                        markers.push({
                            iconPath: "../../img/icon-hc.png",
                            id: 900000000 + parseInt(orders[i].order_id),
                            order_id: orders[i].order_id,
                            select_id: `#card-${orders[i].order_id}` ,
                            latitude: orders[i].latitude,
                            longitude: orders[i].longitude,
                            width: 23,
                            height: 23,
                            callout: {
                                content: orders[i].contact ,
                                fontSize: 14,
                                padding: true,
                                color: '#444',
                                display: 'ALWAYS',
                                textAlign: 'center',
                                borderRadius: 5,
                                bgColor: '#ffffff'
                            },
                        })

                    }

                    that.setData({
                        markers,
                        orders,
                        total_deliver_fee
                    })
                    Notify({
                        type: 'success',
                        message: '数据加载完成'
                    });

                }
            }
        })
    },
    //根据距离计算远近
    sort_orders(orders) {
        let arr = newArray;
        let s = "";
        for (var i = 1; i < arr.length; i++) {
          for (var j = i; j > 0; j--) {
            if (arr[j].distance > arr[j - 1].distance) {
              s = arr[j];
              arr[j] = arr[j - 1];
              arr[j - 1] = s;
            }
          }
        }
       return newArray.reverse();
       
      },
    // 经纬度计算距离

    getDistance( lat1,  lng1,  lat2,  lng2){
        var radLat1 = lat1*Math.PI / 180.0;
        var radLat2 = lat2*Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s *6378.137 ;// EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        s = s.toFixed(2);
        return parseFloat(s);
    },


    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
       //this.get_waiting_delivery()
       //wx.stopPullDownRefresh()

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
       
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //点击导航事件
    getLocation(e) {
        const that = this
        let index = e.currentTarget.dataset['index']; //获取传递的参数
        let order = that.data.orders[index]

        var address = order.address
        var contact = order.contact
        var mobile = order.mobile
        var latitude = order.latitude
        var longitude =order.longitude
        wx.openLocation({
            latitude: Number(latitude), //要去的纬度-地址 一定不要使数字
            longitude: Number(longitude), //要去的经度-地址
            address: address,
            name: contact + '/' + mobile,
            scale: 15
        })
    },
    //点击展开
    onAddress(event) {
        this.setData({
            activeNames: event.detail,
        });
    },
    queryOrder(e) {
        let order_no = e.currentTarget.dataset.order_no
        console.log(order_no)
        this.getViewOrderInfo(order_no)
    },

    getViewOrderInfo(order_no) {
        wx.request({
            url: app.globalData.API + '/delivery/index/query-order-info',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                order_no
            },
            success(res) {
                if (res.data.code === 200) {
                    const success = res.data.data;
                    if (success) {
                        let orderInfo = JSON.stringify(res.data.data)
                        console.log( 'orderInfo:', orderInfo)
                        wx.navigateTo({
                            url: '/templates/deliver/pages/orderInfo/orderInfo',
                            success(res) {
                                res.eventChannel.emit('orderInfo', orderInfo)
                            }
                        })
                    }
                }
            }
        })
    },
    orderBydata(event){
        var order_id = event.target.dataset.id;
        var name = event.target.dataset.name;
        wx.navigateTo({
            url: '/templates/deliver/pages/order/order?order_id='+ order_id+'&name='+name,
        })
    }
})